package app.config;

import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * shiro的配置类
 */
@Configuration
public class ShiroConfig {
    @Autowired
    private MyRealm myRealm;

    @Bean
    public DefaultWebSecurityManager defaultWebSecurityManager(){
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        securityManager.setRealm(myRealm);
        return securityManager;
    }

    @Bean("shiroFilterFactoryBean")
    public ShiroFilterFactoryBean filterFactoryBean(DefaultWebSecurityManager securityManager){
        ShiroFilterFactoryBean filterFactoryBean = new ShiroFilterFactoryBean();
        filterFactoryBean.setSecurityManager(securityManager);
        //添加过滤
        Map<String,String> shiroMap = new LinkedHashMap<>();
        shiroMap.put("/mypage","authc");
        shiroMap.put("/musiclistCreat","authc");
        shiroMap.put("/musicupload","authc");


        shiroMap.put("/login","anon");
        shiroMap.put("/main","anon");
        shiroMap.put("/musiclist","anon");
        shiroMap.put("/musiclistShow","anon");
        shiroMap.put("/musicrank","anon");
        shiroMap.put("/musicruning","anon");
        shiroMap.put("/musicOnLineRuning","anon");
        shiroMap.put("/visual","anon");
        shiroMap.put("/connectUs","anon");
        shiroMap.put("/logout","logout");

        filterFactoryBean.setFilterChainDefinitionMap(shiroMap);
        //被拦截的页面则跳转到自定义页面
        filterFactoryBean.setLoginUrl("/login");
        //设置未经授权的页面
        filterFactoryBean.setUnauthorizedUrl("unAuth");
        return filterFactoryBean;
    }

    //开启注解代理
    @Bean
    public AuthorizationAttributeSourceAdvisor newAuthorizationAttributeSourceAdvisor(
            SecurityManager securityManager){
        AuthorizationAttributeSourceAdvisor bean= new AuthorizationAttributeSourceAdvisor();
        bean.setSecurityManager(securityManager);
        return bean;
    }
}
